const localVideoEle = document.getElementById('local-video');
const remoteVideoEle = document.getElementById('remote-video');
const baseUrl = '192.168.1.29';
// const baseUrl = "192.168.31.144";
// const baseUrl = '192.168.3.14';

function initSocket(url) {
    const socket = new WebSocket(`wss://${url}`);
    socket.onopen = () => console.log('信令通道创建成功！')
    socket.onerror = () => console.error('信令通道创建失败！');
    return socket
}

const socket = initSocket(baseUrl)


let userId
function login() {
    userId = prompt("请输入你的ID")
    document.title = userId
    setTimeout(() => {
        socket.send(JSON.stringify({
            type: 'login',
            from: userId,
            to: 'service'
        }))
    }, 1000)

}


function onStatusChange(status) {
    console.log('onStatusChange---', status)
    const hangupBtn = document.getElementById('hangup')
    const callBtn = document.getElementById('call')
    if (status === 'free') {
        hangupBtn.style.display = 'none'
        callBtn.style.display = 'inline-block'
    } else {
        hangupBtn.style.display = 'inline-block'
        callBtn.style.display = 'none'
    }
}

function callConfirm() {
    return new Promise((resolve) => {
        const flag = confirm('确定接听吗？')
        resolve(flag)
    })
}

function call() {
    const otherId = prompt('请输入对方ID')
    if(otherId != null){
        videoCall.call(otherId)
    }
    
}


login()

const videoCall = new VideoCall({
    socket,
    userId,
    timeout: 5 * 1000,
    confirm: callConfirm,
    onStatusChange: onStatusChange,
    remoteVideoEle: remoteVideoEle,
    localVideoEle: localVideoEle,
    onMessage: ({ type, message }) => {
        if (type === 'error') {
            alert(message)
        }
    }
});